import { Inject, Injectable } from '@nestjs/common';
import { MicroserviceConfig } from './microservice-gateway.module';

@Injectable()
export class MicroserviceGatewayService {
  private routeMap: Map<string, string> = new Map();

  constructor(
    @Inject('MICROSERVICE_CONFIGS') private configs: MicroserviceConfig[],
  ) {
    // 构建路由映射
    this.configs.forEach(config => {
      const prefix = config.routePrefix || config.name;
      this.routeMap.set(prefix, config.name);
    });
  }

  getServiceNameByRoute(route: string): string | null {
    // 查找匹配的路由前缀
    for (const [prefix, serviceName] of this.routeMap.entries()) {
      if (route === prefix || route.startsWith(`${prefix}/`)) {
        return serviceName;
      }
    }
    return null;
  }

  getPathWithoutPrefix(route: string): string {
    for (const prefix of this.routeMap.keys()) {
      if (route === prefix) {
        return 'default';
      }
      if (route.startsWith(`${prefix}/`)) {
        return route.substring(prefix.length + 1);
      }
    }
    return route;
  }
}